// app.js
const request = require('./utils/request');

App({
  // 全局数据
  globalData: {
    userInfo: null,
    token: null,
    refresh_token: null,
    baseUrl: 'http://175.27.235.138'
  },
  
  // 生命周期函数--监听小程序初始化
  onLaunch: function() {
    // 从本地存储获取token
    const token = wx.getStorageSync('token');
    if (token) {
      this.globalData.token = token;
    }
    
    // 从本地存储获取refresh_token
    const refresh_token = wx.getStorageSync('refresh_token');
    if (refresh_token) {
      this.globalData.refresh_token = refresh_token;
    }
    
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.globalData.userInfo = userInfo;
    }
  },
  
  // 封装的网络请求
  request: request,
  
  // 设置token
  setToken: function(token) {
    this.globalData.token = token;
    wx.setStorageSync('token', token);
  },
  
  // 获取token
  getToken: function() {
    return this.globalData.token;
  },
  
  // 清除token
  clearToken: function() {
    this.globalData.token = null;
    wx.removeStorageSync('token');
  },
  
  // 设置refresh_token
  setRefreshToken: function(refresh_token) {
    this.globalData.refresh_token = refresh_token;
    wx.setStorageSync('refresh_token', refresh_token);
  },
  
  // 获取refresh_token
  getRefreshToken: function() {
    return this.globalData.refresh_token;
  },
  
  // 清除refresh_token
  clearRefreshToken: function() {
    this.globalData.refresh_token = null;
    wx.removeStorageSync('refresh_token');
  },
  
  // 设置用户信息
  setUserInfo: function(userInfo) {
    this.globalData.userInfo = userInfo;
    wx.setStorageSync('userInfo', userInfo);
  },
  
  // 获取用户信息
  getUserInfo: function() {
    return this.globalData.userInfo;
  },
  
  // 清除用户信息
  clearUserInfo: function() {
    this.globalData.userInfo = null;
    wx.removeStorageSync('userInfo');
  },
  
  // 退出登录
  logout: function() {
    this.clearToken();
    this.clearRefreshToken();
    this.clearUserInfo();
    wx.reLaunch({
      url: '/pages/index/index'
    });
  }
});